﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LaunchySharp;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Threading;
using LingvoTranslate.Properties;
using System.Windows.Forms;

namespace LingvoTranslate
{
    public class LinvoYandex : IPlugin
    {
        #region IPlugin Members

        private IPluginHost _pluginHost = null;
        private ICatItemFactory _catItemFactory = null;
        private uint _id = 0;
        private string _pluginName = "LingvoYandex";

        public void init(IPluginHost pluginHost)
        {
            _pluginHost = pluginHost;

            if (_pluginHost != null)
            {
                _catItemFactory = _pluginHost.catItemFactory();
                _id = _pluginHost.hash(_pluginName);
            }
        }

        public uint getID()
        {
            return _id;
        }

        public string getName()
        {
            return _pluginName;
        }

        public void getLabels(List<IInputData> inputDataList)
        {
            var input = inputDataList[0];

            if ("translate".StartsWith(input.getText().ToLower()))
                input.setLabel(getID());
        }

        public void getResults(List<IInputData> inputDataList, List<ICatItem> resultsList)
        {
            string iconPath = Path.Combine(_pluginHost.launchyPaths().getIconsPath(), "LinvoYandex.ico");

            string toTranslate = inputDataList.Last().getText();

            if (inputDataList.Count == 1)
            {
                var words = toTranslate.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                // Single words probably require translation, phrases - something else (googling?)
                var usage = words.Length == 1 ? 1 : 0;

                var catItem = _catItemFactory.createCatItem(
                    string.Format("Translate '{0}' with Linvo.Yandex", toTranslate),
                    "Translate", getID(), iconPath, (uint)usage);

                resultsList.Add(catItem);
                inputDataList.Last().setTopResult(catItem);
            }
            else if (inputDataList[0].hasLabel(getID()))
            {
                resultsList.Add(_catItemFactory.createCatItem(toTranslate, toTranslate, getID(), iconPath));
            }
        }

        public void getCatalog(List<ICatItem> catalogItems)
        {
        }

        public void launchItem(List<IInputData> inputDataList, ICatItem item)
        {
            var words = inputDataList.Where(i => !i.hasLabel(getID())).Select(i => i.getText());

            foreach (var word in words)
            {
                string webUrl = string.Format(@"http://lingvo.yandex.ru/en?text={0}&st_translate=on", Uri.EscapeUriString(word));
                Process.Start(webUrl);
                LogTranslationRequest(word);
                Thread.Sleep(100);
            }
        }

        private void LogTranslationRequest(string word)
        {
            try
            {
                string logPath = Settings.Default.GetWordLogPathCanonical();
                Directory.CreateDirectory(Path.GetDirectoryName(logPath));
                File.AppendAllText(logPath, word + Environment.NewLine);
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    "This message will not be displayed any more until Launchy restarted" + Environment.NewLine + ex.ToString(), 
                    "Error writing word to log");
            }
        }

        TranslatorOptionsControl _optionsControl = new TranslatorOptionsControl();

        public bool hasDialog()
        {
            return true;
        }

        public IntPtr doDialog()
        {
            _optionsControl.Show();
            return _optionsControl.Handle;
        }

        public void endDialog(bool acceptedByUser)
        {
            if (acceptedByUser)
                Settings.Default.Save();
            else
                Settings.Default.Reload();
        }

        public void launchyShow()
        {
        }

        public void launchyHide()
        {
        }

        #endregion
    }
}
